package com.rk.admin.aop;
import com.rk.admin.domain.ApiCount;
import com.rk.admin.mapper.ApiMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@Aspect
public class ApiVisCount {

    @Autowired
    private ApiMapper apiMapper;
    private Logger log = LoggerFactory.getLogger(ApiVisCount.class);
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    //Controller层切点
    @Pointcut("@annotation(VisCongtrollerApi)")
    public void controllerAspect(){
    }


    /**
     * 在接口原有的方法执行前，将会首先执行此处的代码
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        System.out.println("对应的进入时间："+startTime);

        Date d1 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(d1);
        System.out.println("对应的Date："+dateNowStr);

        Date date1 = sdf.parse(dateNowStr);
        java.sql.Date today = new java.sql.Date(date1.getTime());

        if((apiMapper.finddata(today))>0){
            ApiCount api = new ApiCount();
            api.setCounts(apiMapper.findcount( today));
            System.out.println("查询的总数："+api.getCounts());
            apiMapper.updatelist(api.getCounts()+1, today);
        }else{
            apiMapper.savelist(1);
        }

    }


    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     * @date
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }


}
